package com.leetcode.tree.bst;

import com.leetcode.basic.TreeNode;

/**
 * @author Dennis Li
 * @date 2020/10/16 16:38
 */
public class DeleteNode_450 {
    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else if (root.val < key){
            root.right = deleteNode(root.right, key);
        } else {
            if (root.right == null && root.left == null) {
                root = null;
            } else if (root.left == null || root.right == null) {
                root = root.right == null ? root.left : root.right;
            } else {
                // 找右子树的最小值
                TreeNode min = getMin(root.right);
                // 赋值
                root.val = min.val;
                // 将右部分的子树进行调整，这次需要删除的是最小值的点
                root.right = deleteNode(root.right, min.val);
            }
        }
        return root;
    }

    private TreeNode getMin(TreeNode root) {
        while (root.left != null) {
            root = root.left;
        }
        return root;
    }

}
